package com.example.module_motocircle.adpater

import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.recyclerview.widget.DiffUtil
import androidx.recyclerview.widget.RecyclerView
import com.example.module_motocircle.R
import com.example.module_motocircle.databinding.LayoutPostItemBinding
import com.example.module_motocircle.model.PostItem
import com.example.module_motocircle.post.PostDiffCallBack
import java.util.Collections


class PostListAdapter(
    private val onItemClick: ((PostItem, Int) -> Unit)? = null,
    private val onUserClick: ((PostItem) -> Unit)? = null,
//    private val onImageClickWithThumbnail: ((Int, Int, List<Image>, List<Info>) -> Unit)? = null,
    private val onShareClick: ((PostItem) -> Unit)? = null,
    private val onCommentsClick: ((PostItem) -> Unit)? = null,
    private val onLikeClick: ((PostItem, Int) -> Unit)? = null,
    private val onMoreActionClick: ((PostItem, Int) -> Unit)? = null,
    private val onLikeViewClick: ((PostItem, Int, View) -> Unit)? = null,
    private val onCollectionViewClick: ((PostItem, Int, View) -> Unit)? = null,
    private val onFollowViewClick: ((PostItem, Int, View) -> Unit)? = null,
    // 是否显示关系
    private val showRelationState: Boolean = true,
    private val onPreload:(()->Unit)? = null,
    private var preloadItemCount:  Int = 0, //预加载偏移量，倒数第几个
): RecyclerView.Adapter<PostViewHolder>() {
    private val mData = mutableListOf<PostItem>()
    private var scrollState = RecyclerView.SCROLL_STATE_IDLE//滚动状态
    override fun onAttachedToRecyclerView(recyclerView: RecyclerView) {
        recyclerView.addOnScrollListener(object : RecyclerView.OnScrollListener(){
            override fun onScrollStateChanged(recyclerView: RecyclerView, newState: Int) {
                scrollState = newState
                super.onScrollStateChanged(recyclerView, newState)
            }
        })
    }

    fun setData(data:List<PostItem>){
        val calculateDiff = DiffUtil.calculateDiff(PostDiffCallBack(mData.toList(), data))
        mData.clear()
        mData.addAll(data)
        val size = mData.size
//        notifyItemRangeInserted(size-1,data.size)
        calculateDiff.dispatchUpdatesTo(this)
    }

    /**
     * 追加数据,范围局部刷新
     */
    fun addData(newData:List<PostItem>){
        val size = newData.size
        mData.addAll(newData)
        notifyItemRangeInserted(size-1,newData.size)
    }
    fun addData(myPost: PostItem){
        mData.add(myPost)
        notifyItemInserted(mData.size)
    }

    fun removeData(position:Int){
        mData.removeAt(position)
        notifyItemRemoved(position)
    }

    fun moveData(from:Int,to:Int){
        Collections.swap(mData,from,to)
        notifyItemMoved(from,to)
    }

    /**
     * 判断是否加载
     */
    private fun checkPreLoad(position: Int){
        if (onPreload != null && scrollState != RecyclerView.SCROLL_STATE_IDLE && position == mData.size - preloadItemCount -1){
            onPreload.invoke()
        }
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): PostViewHolder {
        val binding = LayoutPostItemBinding.inflate(LayoutInflater.from(parent.context),parent,false)
        return PostViewHolder(
            onItemClick = onItemClick,
            onUserClick = onUserClick,
//            onImageClickWithThumbnail = onImageClickWithThumbnail,
            onShareClick = onShareClick,
            onCommentsClick = onCommentsClick,
            onLikeClick = onLikeClick,
            onMoreActionClick = onMoreActionClick,
            onLikeViewClick = onLikeViewClick,
            onCollectionViewClick = onCollectionViewClick,
            onFollowViewClick = onFollowViewClick,
            mBinding = binding)
    }

    override fun getItemCount(): Int {
        return mData.size
    }

    override fun onBindViewHolder(
        holder: PostViewHolder,
        position: Int,
        payloads: MutableList<Any>
    ) {
        //判断是否到达倒数第几个
        checkPreLoad(position)
        if (payloads.isEmpty()){
            super.onBindViewHolder(holder, position, payloads) //注意！！
        }else{
            holder.mBinding.apply {
                if(mData[position].if_like == 1){
                    ivLike.setImageResource(R.mipmap.icon_like_checked)
                }else{
                    ivLike.setImageResource(R.mipmap.icon_like)
                }
                if(mData[position].if_collect == 1){
                    ivCollection.setImageResource(R.mipmap.icon_collection_checked)
                }else{
                    ivCollection.setImageResource(R.mipmap.icon_collection)
                }
                tvLike.text = mData[position].formatLikeNumber()
                tvCollection.text = mData[position].formatCollectionNumber()
                tvShare.text = mData[position].formatShareNumber()
            }
        }
    }

    override fun onBindViewHolder(holder: PostViewHolder, position: Int) {
        mData[position].needShowFollowState = showRelationState
        //databinding数据绑定
        holder.mBinding.holder = holder
        holder.mBinding.post = mData[position]

        //自己处理部分UI绑定
        holder.initView(mData[position],position)

    }
    fun getItemByPosition(position:Int):PostItem?{
        if (position < 0 || position >= mData.size ){
            return null
        }
        return mData[position]
    }

    /**
     * 局部增量刷新
     */
    fun updatePostItem(postItem: PostItem){
        repeat(itemCount){
            val  item = mData[it]
            if (item.posts_id == postItem.posts_id){
                item.apply {
                    if_like = postItem.if_like
                    if_collect = postItem.if_collect
                    like_number = postItem.like_number
                    collect_number = postItem.collect_number
                    share_number = postItem.share_number
                    notifyItemChanged(it,"update")
                    return
                }
            }

        }

    }
    fun getPostItem(position:Int):PostItem{
        return mData[position]
    }
}